const DistModel = require('../../db/models/dist');

// 查询字典列表（包括条件查询）
const queryDistList = async function (ctx, next) {
  let params = ctx.request.query;
  let reg = new RegExp(params.name, 'i');
  let distList = await DistModel.find({
    $or: [{ name: { $regex: reg } }]
  });
  ctx.body = distList;
}

// 添加字典类
const addDist = async function (ctx, next) {
  let data = ctx.request.body;
  await DistModel.create(data).then(() => {
    ctx.body = {
      success: true
    }
  }).catch(err => {
    ctx.body = {
      success: false,
      msg: err.message
    }
  })
}

// 删除字典类
const deleteDist = async function (ctx, next) {
  let params = ctx.request.query;
  await DistModel
    .deleteMany({ _id: { $in: params._id.split(',') } })
    .then(() => {
      ctx.body = {
        success: true
      }
    })
    .catch(err => {
      ctx.body = {
        success: false,
        msg: err.message
      }
    })
}

// 更新字典
const updateDist = async function (ctx, next) {
  let data = ctx.request.body;
  await DistModel
    .where({ _id: data._id })
    .update(data)
    .then(() => {
      ctx.body = {
        success: true
      }
    })
    .catch(err => {
      ctx.body = {
        success: false,
        msg: err.message
      }
    })
}

// 查询单个字典信息
const queryOneDist = async function (ctx, next) {
  let params = ctx.request.query;
  await DistModel.find(params).then(res => {
    ctx.body = {
      success: true,
      data: res
    }
  }).catch(err => {
    ctx.body = {
      success: false,
      msg: err.message
    }
  })
}

// 向单个字典中添加字典项
const addDistItem = async function (ctx, next) {
  let data = ctx.request.body;
  await DistModel
    .where({ _id: data._id })
    .updateOne({ values: data.value })
    .then(() => {
      ctx.body = {
        success: true
      }
    })
    .catch(err => {
      ctx.body = {
        success: false,
        msg: err.message
      }
    })
}

module.exports = {
  queryDistList,
  addDist,
  deleteDist,
  updateDist,
  queryOneDist,
  addDistItem
}